package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.behavior.dto.EntryDto;
import com.heima.behavior.dto.FollowBehaviorDto;
import com.heima.behavior.entity.ApBehaviorEntry;
import com.heima.behavior.entity.ApFollowBehavior;
import com.heima.behavior.mapper.ApFollowBehaviorMapper;
import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApFollowBehaviorService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * APP关注行为表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-03-17
 */
@Service
public class ApFollowBehaviorServiceImpl extends ServiceImpl<ApFollowBehaviorMapper, ApFollowBehavior> implements IApFollowBehaviorService {


    @Autowired
    private IApBehaviorEntryService entryService;

    @Override
    public void saveFollow(FollowBehaviorDto dto) {
        // 根据用户id和设备id查询行为实体
        EntryDto entryDto = new EntryDto();
        entryDto.setEquipmentId(dto.getEquipmentId());
        entryDto.setUserId(dto.getUserId());
        ApBehaviorEntry entry = entryService.getEntry(entryDto);
        // 构建关注行为记录
        ApFollowBehavior followBehavior = new ApFollowBehavior();
        followBehavior.setEntryId(entry.getId());
        followBehavior.setFollowId(dto.getFollowId());
        followBehavior.setOperation(dto.getOperation());
        followBehavior.setCreatedTime(new Date());
        // 保存行为记录
        // 查询历史记录
        LambdaQueryWrapper<ApFollowBehavior> query = new LambdaQueryWrapper<>();
        query.eq(ApFollowBehavior::getEntryId, entry.getId());
        query.eq(ApFollowBehavior::getFollowId, dto.getFollowId());
        ApFollowBehavior one = this.getOne(query);
        if (one == null) {
            // 判断当前的操作类型
            if (dto.getOperation() == 0) {
                // 新增
                this.save(followBehavior);
            }
        } else {
            // 判断当前操作和数据库操作是否一致,不一致才进行处理
            if (one.getOperation() != dto.getOperation()) {
                one.setOperation(dto.getOperation());
                this.updateById(one);
            }
        }

    }
}

